package com.life.util;

import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.StringTokenizer;
import java.util.UUID;

public class StringUtil {
	public static String[] toArray(String target, String delim) {
		if (target == null)
			return new String[0];
		StringTokenizer st = new StringTokenizer(target, delim);
		String[] result = new String[st.countTokens()];
		int i = 0;

		while (st.hasMoreTokens()) {
			result[i] = st.nextToken();
			i++;
		}
		return result;
	}
	 
	public static String genUid(){
		return UUID.randomUUID().toString();
	}
	
	
	public static String arrayToStr(String[] arr) {
		String str=null;
		if (arr == null)
			return "";
		else{
			for (int i = 0; i < arr.length; i++) {
				str += arr[i] + "\r\n";
			}
		}
		return str;
	}

	public static String replaceStr(String str, String oldStr, String newStr) {
		int s = 0;
		int e = 0;
		int ol = oldStr.length();
		StringBuffer result = new StringBuffer();

		while ((e = str.indexOf(oldStr, s)) >= 0) {
			result.append(str.substring(s, e));
			result.append(newStr);
			s = e + ol;
		}
		result.append(str.substring(s));
		return result.toString();
	}

	public static String ConvertToStr(Object obj) {
		String str = "";
		if (!isEmpty(obj)) {
			str = obj.toString().trim();
		}
		return str;
	}

	public static String ConvertDbStrToStr(Object obj) {
		String str = "";
		if (!isEmpty(obj)) {
			str = obj.toString().trim().toLowerCase();
		}
		if (str.contains("_")) {
			String[] tmp = str.split("_");
			int length = tmp.length;
			str = tmp[0];
			for (int i = 1; i < length; i++) {
				String strtmp = tmp[i];
				str += strtmp.substring(0, 1).toUpperCase() + strtmp.substring(1, strtmp.length());
			}
		}
		return str;
	}

	public static String ConvertToStrs(Object obj) {
		String str = " ";
		if (!isEmpty(obj)) {
			str = obj.toString().trim();
		}
		return str;
	}
	
	public static boolean isEmpty(List list){
		for (int i = 0; i < list.size(); i++) {
			if(isEmpty(list.get(i))){
				return true;
			}
		}
		return false;
	}

	public static boolean isEmpty(Object obj) {
		boolean result = true;
		try {
			if (obj == null)
				return true;
			Class<? extends Object> cls = obj.getClass();

			if (cls.isArray()) {
				Object[] objs = (Object[]) obj;
				if (objs.length > 0) {
					result = false;
				}
			}
			if (obj instanceof String && !obj.toString().trim().equals("")) {
				result = false;
			}
			if (obj instanceof Collection) {
				@SuppressWarnings(value = { "unchecked" })
				Collection coll = (Collection) obj;
				if (!coll.isEmpty()) {
					result = false;
				}
			}
			if (obj instanceof Map) {
				@SuppressWarnings(value = { "unchecked" })
				Map map = (Map) obj;
				if (!map.isEmpty()) {
					result = false;
				}
			}
			if (obj instanceof Number) {
				Number num = (Number) obj;
				if (!num.toString().trim().equals(""))
					result = false;
			}
			if (obj instanceof Double) {
				Double dou = (Double) obj;
				if (!dou.toString().trim().equals(""))
					result = false;
			}
			if (obj instanceof Float) {
				Float fla = (Float) obj;
				if (!fla.toString().trim().equals(""))
					result = false;
			}
			if (obj instanceof Date) {
					result = false;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}

	public static String ConvertDecToStr(Object obj, String code) {
		String str = ConvertToStr(obj);
		try {
			if (!str.equals(""))
				str = URLDecoder.decode(str, code);
		} catch (Exception e) {
			// SaveStackTrace(e);
		}
		return str;
	}

	public static String wrapClauses(String[] strs) {
		if (strs == null || strs.length == 0)
			return "('')";
		String rel = "(";
		for (int i = 0; i < strs.length; i++) {
			rel += "'" + strs[i] + "',";
		}
		rel = removeEnd(rel, ",");
		return rel + ")";
	}

	public static String wrapClause(String[] strs) {
		String rel = "";
		for (int i = 0; i < strs.length; i++) {
			rel += "'" + strs[i] + "',";
		}
		rel = removeEnd(rel, ",");
		return rel;
	}

	public static String wrapClauseList(Map<String, List<String>> map) {
		String rel = "";
		if (!isEmpty(map)) {
			for (Iterator<String> iter = map.keySet().iterator(); iter.hasNext();) {
				String fieldName = iter.next();
				List<String> valObj = map.get(fieldName);
				rel += " " + fieldName + " in " + wrapMidList(valObj) + " and";
			}
			rel = removeEnd(rel, "and");
		}
		return rel;
	}

	public static String wrapClauseStringArray(Map<String, String[]> map) {
		String rel = "";
		if (!isEmpty(map)) {
			for (Iterator<String> iter = map.keySet().iterator(); iter.hasNext();) {
				String fieldName = iter.next();
				String[] valObj = map.get(fieldName);
				rel += " " + fieldName + " in " + wrapClauses(valObj) + " and";
			}
			rel = removeEnd(rel, "and");
		}
		return rel;
	}

	public static String wrapClauseString(Map<String, String> map) {
		String rel = "";
		if (!isEmpty(map)) {
			for (Iterator<String> iter = map.keySet().iterator(); iter.hasNext();) {
				String fieldName = (String) iter.next();
				String valObj = map.get(fieldName);
				rel += " " + fieldName + " = " + valObj + " and";
			}
			rel = removeEnd(rel, "and");
		}
		return rel;
	}

	public static String wrapMidList(List<String> detailMidList) {
		if (detailMidList == null || !(detailMidList.size() > 0))
			return "('')";
		String imidStr = "(";
		for (Iterator<String> iter = detailMidList.iterator(); iter.hasNext();) {
			String str = iter.next();
			if (iter.hasNext()) {
				imidStr += "'" + str + "',";
			} else {
				imidStr += "'" + str + "')";
			}

		}
		return imidStr;
	}

	public static List<String> CoverToList(String data) {
		List<String> list = new ArrayList<String>();
		if (data != null && !data.trim().equals("")) {
			String datas[] = data.split(",");
			int num = datas.length;
			for (int i = 0; i < num; i++)
				list.add(datas[i]);
		}
		return list;
	}

	public static String removeEnd(String str, String remove) {
		if (str.equals("") || remove.equals(""))
			return str;
		if (str.endsWith(remove))
			return str.substring(0, str.length() - remove.length());
		else
			return str;
	}

	public static String convertBig5ToUnicode(Object obj) {
		try {
			return new String(ConvertToStr(obj).getBytes("Big5"), "ISO8859_1");
		} catch (java.io.UnsupportedEncodingException e) {
			e.printStackTrace();
			return "";
		}
	}

	public static String convertToUnicode(Object obj) {
		try {
			return new String(ConvertToStr(obj).getBytes(), "ISO8859_1");
		} catch (java.io.UnsupportedEncodingException e) {
			e.printStackTrace();
			return "";
		}
	}

	public static String convertUnicodeToBig5(Object obj) {
		try {
			return new String(ConvertToStr(obj).getBytes("ISO8859_1"), "Big5");
		} catch (java.io.UnsupportedEncodingException e) {
			e.printStackTrace();
			return "";
		}
	}

	public static String convertUnicodeToGbk(Object obj) {
		try {
			return new String(ConvertToStr(obj).getBytes("utf-8"), "GBK");
		} catch (java.io.UnsupportedEncodingException e) {
			e.printStackTrace();
			return "";
		}
	}

	public static String convertUnicodeToUtf8(Object obj) {
		try {
			return new String(ConvertToStr(obj).getBytes("ISO8859_1"), "utf-8");
		} catch (java.io.UnsupportedEncodingException e) {
			e.printStackTrace();
			return "";
		}
	}
	public static String convertUtf8ToUnicode(Object obj) {
		try {
			return new String(ConvertToStr(obj).getBytes("utf-8"), "ISO8859_1");
		} catch (java.io.UnsupportedEncodingException e) {
			e.printStackTrace();
			return "";
		}
	}
	public static String convertLatin1ToUtf8(Object obj) {
		try {
			return new String(ConvertToStr(obj).getBytes("Latin1"), "utf-8");
		} catch (java.io.UnsupportedEncodingException e) {
			e.printStackTrace();
			return "";
		}
	}

	public static String convertToUtf8(Object obj) {
		try {
			return new String(ConvertToStr(obj).getBytes(), "utf-8");
		} catch (java.io.UnsupportedEncodingException e) {
			e.printStackTrace();
			return "";
		}
	}

	public static String convertBig5ToUtf8(Object obj) {
		try {
			return new String(ConvertToStr(obj).getBytes("Big5"), "utf-8");
		} catch (java.io.UnsupportedEncodingException e) {
			e.printStackTrace();
			return "";
		}
	}

	public static String convertUtfToBig5(Object obj) {
		try {
			return new String(ConvertToStr(obj).getBytes("utf-8"), "Big5");
		} catch (java.io.UnsupportedEncodingException e) {
			e.printStackTrace();
			return "";
		}
	}

	public static String splitList(List<String> list) {
		String result = "";
		if (isEmpty(list)) {
			for (Iterator<String> iter = list.iterator(); iter.hasNext();) {
				String str = iter.next();
				result += str + "##";
			}
			result = removeEnd(result, "##");
		}
		return result;
	}
	/**1、规避valueOf输出null；2、Number类型的Object转toString的格式*/
	public static String get(Object from){
	  String value="";
	  if(from!=null){ //2、未实现
	    value=String.valueOf(from);
	  }
	  return value;
	}
	
	public static String replaceText(String text)
    {
        
        text = text.replace("\r\n", "<br/>&nbsp;&nbsp;");//这才是正确的！
        text = text.replace("\t", "&nbsp;&nbsp;&nbsp;&nbsp;");
        text = text.replace(" ", "&nbsp;");
        return text;

    }
	
	public static String replaceToBean(String s){
		int m = 0;
		//String s="meta_area_code";
		StringBuffer sb;
		int t=0;
		while((t=s.indexOf("_",m))>0){
			sb=new StringBuffer();
			sb.append(s.substring(0,t));
			sb.append(s.substring(t+1, t+2).toUpperCase());
			sb.append(s.substring(t+2,s.length()));
			m = t + 1;
			s=sb.toString();
		}
		return s;
	}

	public static String utf8Togb2312(String str){
	      StringBuffer sb = new StringBuffer();
	      for(int i=0; i<str.length(); i++) {
	          char c = str.charAt(i);
	          switch (c) {
	             case '+':
	                 sb.append(' ');
	             break;
	             case '%':
	                 try {
	                      sb.append((char)Integer.parseInt(
	                      str.substring(i+1,i+3),16));
	                 }
	                 catch (NumberFormatException e) {
	                     throw new IllegalArgumentException();
	                }
	                i += 2;
	                break;
	             default:
	                sb.append(c);
	                break;
	           }
	      }
	      // Undo conversion to external encoding
	      String result = sb.toString();
	      String res=null;
	      try{
	          byte[] inputBytes = result.getBytes("8859_1");
	          res= new String(inputBytes,"UTF-8");
	      }
	      catch(Exception e){}
	      return res;
	} 
	
	public static Boolean isStrEmpty(String s){
		if(s==null||s.isEmpty())return true;else return false;
	}

	public static Boolean isStrEmpty(String [] s){
		Boolean isEmpty=false;
		for(String str:s){
			if(isStrEmpty(str))return true;
		}
		return isEmpty;
	}
	
	/**
	 * 数组字符串都不为空
	 * */
	public static Boolean isNotEmptyAll(String [] s){
		Boolean isEmpty=true;
		for(String str:s){
			if(isStrEmpty(str))return false;
		}
		return isEmpty;
	}
	
	/**
	 * 数组字符串都为空
	 * */
	public static Boolean isEmptyAll(String [] s){
		Boolean isEmpty=true;
		for(String str:s){
			if(!isStrEmpty(str))isEmpty=false;
		}
		return isEmpty;
	}
	
	public static String convertArrToStr(Object o[]){
		StringBuffer sb=new StringBuffer();
		for(Object obj:o){
			sb.append(obj+",");
		}
		return sb.toString();
	}
	
	public static String convertArrToRawStr(Object o[]){
		StringBuffer sb=new StringBuffer();
		for(Object obj:o){
			sb.append(obj);
		}
		return sb.toString();
	}
	
	public static String fileLast(String name){
		if(StringUtil.isStrEmpty(name))return "";
		int f=name.lastIndexOf(".");
		if(f==-1)return"";
		String fileName=name.substring(name.lastIndexOf("."));
		return fileName;
	}
	
	public static String genFileNameInDb(String userid,Date date,String fileName,String index){
		return userid+"_"+DateUtil.FormatDate(date, "yyyyMMddHHmmss")+"_"+index+StringUtil.fileLast(fileName);
	}
	
	public static void main(String args[]){
		/*List  inList=new ArrayList();
		inList.add("001");
		inList.add("OE");
		inList.add("OE00113122300001");
		inList.add("lich");
		inList.add(new Date());
		inList.add("2");
		inList.add("0");//是否指定储位
		inList.add("2");//库存是否可移库
		inList.add("0");//分布式定位，任务批次号
		inList.add("1");//作业类型
		inList.add(0==0?1:0);//是否第一张单
		inList.add("N");//原波次号 第一次默认为N 
		Boolean res = StringUtil.isEmpty(inList);
		System.out.println(res);*/
		//System.out.println(convertArrToRawStr("a,b,c".split(",")));
		String a = " abc";
		String b = "lll ";
		String c = " 123 ";
		trimBlankSpace(new String[]{a,b,c});
		System.out.println(a);
		System.out.println(b);
		System.out.println(c);
	}
	
	public static String[] trimBlankSpace(String[] strs)
	{
		for (int i = 0; i < strs.length; i++)
		{
			strs[i] = strs[i].trim();
		}
		return strs;
	}
	
}

